package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.OrderWebSocketConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.*;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;

    @Autowired
    private WebSocketServer webSocketServer;
    /**
     * 提交订单
     * @param ordersSubmitDTO
     * @return
     */
    @Transactional
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        //异常数据处理：（后端也是需要处理，否则不太安全）

            //1.收获地址为空
        Long addressBookId = ordersSubmitDTO.getAddressBookId();
        AddressBook addressBook = addressBookMapper.getById(addressBookId);
        if(addressBook == null){
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
            //2.超出配送范围
        checkOutOfRange(addressBook.getCityName()+addressBook.getDistrictName()+addressBook.getDetail());
            //3.购物车为空
        Long userId = BaseContext.getCurrentId();
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.list(ShoppingCart.builder()
                .userId(userId)
                .build());
        if(shoppingCarts == null || shoppingCarts.isEmpty()){
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        ///////////


        //插入一条订单数据
            //订单信息设置
        Orders order = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,order);
            //收获地址相关的
        order.setPhone(addressBook.getPhone());
        order.setAddress(addressBook.getDetail());
        order.setConsignee(addressBook.getConsignee());
            //其他信息
        order.setNumber(String.valueOf(System.currentTimeMillis()));
        order.setUserId(userId);
        order.setPayStatus(Orders.UN_PAID);
        order.setStatus(Orders.PENDING_PAYMENT);
        order.setOrderTime(LocalDateTime.now());

        orderMapper.insert(order);
        ///////////

        //插入订单详情数据
        List<OrderDetail> orderDetails=new ArrayList<>();
        for(ShoppingCart cart:shoppingCarts){
            OrderDetail orderDetail=new OrderDetail();
            BeanUtils.copyProperties(cart,orderDetail);
            orderDetail.setOrderId(order.getId());
            orderDetails.add(orderDetail);
        }
        orderDetailMapper.insertBatch(orderDetails);
        //////


        //清空用户的购物车
        shoppingCartMapper.deleteByUserId(userId);

        //获取返回结果
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(order.getId())
                .orderNumber(order.getNumber())
                .orderAmount(order.getAmount())
                .orderTime(order.getOrderTime())
                .build();
        return orderSubmitVO;
    }

    @Value("${sky.shop.address}")
    private String shopAddress;
    /**
     * 检查商品是否超过配送范围
     * (调用百度路线规划api)
     * （从实现类中抽象出来的方法，这个实现类中才用得到）
     * @param address
     * @Note 这里黑马设计的不太好，首先就是商店的经纬基本不会变，可以设计成只调用一次获取的接口。
     *          然后就是抽象复用的那些东西了，硬编码有点多
     *          这里我先不改了
     *
     */
    private void checkOutOfRange(String address){
        //获取商店的经纬度
        String shopLngAndLat = getLngAndLat(shopAddress);
        //获取用户收货地址的经纬度坐标
        String userLngAndLat=getLngAndLat(address);
        //获取路径规划
        Map map=new HashMap();
        map.put("ak",ak);
        map.put("origin",shopLngAndLat);
        map.put("destination",userLngAndLat);
        map.put("steps_info","0");//不规划路线详情
        String json = HttpClientUtil.doGet("https://api.map.baidu.com/directionlite/v1/driving", map);
        JSONObject jsonObject = JSON.parseObject(json);
        if(!"0".equals(jsonObject.getString("status"))){
            throw new OrderBusinessException(MessageConstant.ADDRESS_FALSE_GENERATE_ROUTE);
        }
        JSONObject result = jsonObject.getJSONObject("result");
        JSONArray jsonArray= (JSONArray) result.get("routes");
        Integer distance=(Integer)(jsonArray.getJSONObject(0).get("distance"));

        //超出配送范围
        if(distance > 5000){
             throw new OrderBusinessException(MessageConstant.ORDER_OUT_OF_RANGE);
        }
    }

    @Value("${sky.baidu.ak}")
    private String ak;

    /**
     * 调用百度api获取经纬度信息(格式：#{经度},#{维度})
     *
     * @param address
     * @return
     */
    private String getLngAndLat(String address) throws OrderBusinessException{
        Map map=new HashMap();
        map.put("address",address);
        map.put("ak",ak);
        map.put("output","json");
        String shopCoordinate= HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3",map);//坐标
        JSONObject jsonObject = JSON.parseObject(shopCoordinate);
        if(!"0".equals(jsonObject.getString("status"))){
            throw new OrderBusinessException(MessageConstant.ADDRESS_COUNT_NOT_PARSE);
        }
        JSONObject location = jsonObject.getJSONObject("result").getJSONObject("location");
        String lat=location.getString("lat");
        String lng= location.getString("lng");
        String lngAndLat=lat+","+lng;
        return lngAndLat;
    }


    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *  （同时使用websocket再商家端做来单提醒）
     *
     * @param outTradeNo
     * @来单提醒业务规则：
     * 约定服务端发送给客户端浏览器的数据格式为JSON，字段包括：type，orderId，content
     *  - type 为消息类型，1为来单提醒 2为客户催单
     *  - orderId 为订单id
     *  - content 为消息内容
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);

        ////来单提醒////
        Map map=new HashMap();
        map.put(OrderWebSocketConstant.KEY_TYPE,OrderWebSocketConstant.VALUE_TYPE_NEW_ORDER_REMINDER);
        map.put(OrderWebSocketConstant.KEY_ORDER_ID,orders.getId());
        map.put(OrderWebSocketConstant.KEY_CONTENT,"订单号："+outTradeNo);
        //通过WebSocket实现来单提醒，向客户端浏览器推送消息
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
        //////////////
    }

    /**
     * 分页查询历史订单
     * @param ordersPageQueryDTO
     * @return
     */
    public PageResult pageQuery(OrdersPageQueryDTO ordersPageQueryDTO) {
        //设置分页查询条件
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        //对数据库进行分页查询
        Page<Orders> page=orderMapper.pageQuery(ordersPageQueryDTO);

        //查询订单详情，并分装进OrderVO
        List<OrderVO> list=new ArrayList<>();
        if(page != null && page.getTotal()>0){
            for(Orders orders:page){
                Long orderId = orders.getId();
                //查询订单的详情
                List<OrderDetail> orderDetails=orderDetailMapper.getByOrderId(orderId);
                //设置前端返回信息
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders,orderVO);
                orderVO.setOrderDetailList(orderDetails);
                list.add(orderVO);
            }
        }

        return new PageResult(page.getTotal(),list);
    }

    /**
     * 根据订单id获取订单详情
     *
     * @param orderId
     * @return
     */
    public OrderVO orderDetail(Long orderId) {
        Orders order=orderMapper.getById(orderId);
        OrderVO orderVO=new OrderVO();
        BeanUtils.copyProperties(order,orderVO);
        List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(orderId);
        orderVO.setOrderDetailList(orderDetails);
        return orderVO;
    }

    /**
     * 用户取消订单
     * @param id
     */
    public void userCancelById(Long id) throws Exception {
        //根据订单id插叙订单
        Orders order = orderMapper.getById(id);
        //校验订单是否存在
            // （不要交给前端）
        if(order==null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //接下来就是一堆业务规则了:

        //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        if (order.getStatus() > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //订单如果处于待接单状态下取消，执行退款操作
        if(Orders.TO_BE_CONFIRMED.equals(order.getStatus())){
            //调用微信支付退款接口
            //TODO 涉及微信相关请求（不方便完成）：微信退款操作
            //  这里先注释掉了
            /*
            weChatPayUtil.refund(
                    order.getNumber(), //商户订单号
                    order.getNumber(), //商户退款单号
                    new BigDecimal(0.01),//退款金额，单位 元
                    new BigDecimal(0.01));//原订单金额
            */
            //支付状态修改为退款
            order.setPayStatus(Orders.REFUND);
        }
        //更新订单状态、取消原因、取消时间
        order.setStatus(Orders.CANCELLED);
        order.setCancelReason("用户取消");
        order.setCancelTime(LocalDateTime.now());
        orderMapper.update(order);

    }

    /**
     * 再来一单：
     *     重新加入购物车
     * @param orderId
     */
    public void repetition(Long orderId) {
        //当前用户的id
        Long userId=BaseContext.getCurrentId();
        //根据订单id查询订单详情
        List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(orderId);
        //转换成购物车对象
        List<ShoppingCart> shoppingCarts=orderDetails.stream().map(orderDetail -> {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail,shoppingCart,"id");//需忽略掉id
            shoppingCart.setUserId(userId);
            shoppingCart.setCreateTime(LocalDateTime.now());
            return shoppingCart;
        }).collect(Collectors.toList());
        //将购物车对象批量添加到数据库中
        shoppingCartMapper.insertBatch(shoppingCarts);

    }

    /**
     * 各个状态的订单数量统计
     *      //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消 7退款
     * @return
     */
    public OrderStatisticsVO statstics() {
        // 根据状态，分别查询出待接单、待派送、派送中的订单数量
        Integer toBeConfirmed = orderMapper.countByStatus(Orders.TO_BE_CONFIRMED);
        Integer confirmed=orderMapper.countByStatus(Orders.CONFIRMED);
        Integer deliveryInProgress = orderMapper.countByStatus(Orders.DELIVERY_IN_PROGRESS);

        //设置响应结果
        OrderStatisticsVO orderStatisticsVO = OrderStatisticsVO.builder()
                .toBeConfirmed(toBeConfirmed)
                .confirmed(confirmed)
                .deliveryInProgress(deliveryInProgress)
                .build();
        return orderStatisticsVO;
    }

    /**
     * 接单(改变订单状态)
     * @param ordersConfirmDTO
     */
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = Orders.builder()
                .status(Orders.CONFIRMED)
                .id(ordersConfirmDTO.getId())
                .build();
        orderMapper.update(orders);
    }

    /**
     * 拒单
     * @param ordersRejectionDTO
     */
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        //TODO 修改操作
        //  这里先进行了查询操作获得实体类，如果把需要修改的值设置到这个上，会存在一些不需要修改的值
        //  这样有点浪费了
        Orders orderDB = orderMapper.getById(ordersRejectionDTO.getId());
        //只有处于待接单状态的订单才能取消
        if(orderDB == null || !Orders.TO_BE_CONFIRMED.equals(orderDB.getStatus())){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //判断支付状态
        if(Orders.PAID.equals(orderDB.getPayStatus())){
            //商家拒单，如果用户已经支付，需要退款
            log.info("微信退款操作...");
            //TODO 涉及微信相关请求（不方便完成）：微信退款操作
            // 直接注释掉了
            /*
            String refund = weChatPayUtil.refund(
                    orderDB.getNumber(),
                    orderDB.getNumber(),
                    new BigDecimal(0.01),
                    new BigDecimal(0.01));
            log.info("申请退款：{}", refund);
            */
        }
        //拒单需要退款，根据订单id更新订单状态、拒单原因、取消时间
        Orders order=new Orders();
        order.setId(orderDB.getId());
        order.setStatus(Orders.CANCELLED);
        order.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        order.setCancelTime(LocalDateTime.now());
        orderMapper.update(order);

    }

    /**
     * 商家取消订单
     * @param ordersCancelDTO
     */
    public void cancel(OrdersCancelDTO ordersCancelDTO) throws Exception {
        Orders orderDB = orderMapper.getById(ordersCancelDTO.getId());
        //判断是否需要退款
        if(Orders.PAID.equals(orderDB.getPayStatus())){
            log.info("微信退款操作...");
            //TODO 涉及微信相关请求（不方便完成）：微信退款操作
            // 直接注释掉了
            /*
            String refund = weChatPayUtil.refund(
                    orderDB.getNumber(),
                    orderDB.getNumber(),
                    new BigDecimal(0.01),
                    new BigDecimal(0.01));
            log.info("申请退款：{}", refund);
            */
        }
        // 管理端取消订单需要退款，根据订单id更新订单状态、取消原因、取消时间
        Orders order = Orders.builder()
                .id(orderDB.getId())
                .status(Orders.CANCELLED)
                .cancelReason(ordersCancelDTO.getCancelReason())
                .cancelTime(LocalDateTime.now()).build();
        orderMapper.update(order);
    }

    /**
     * 派送订单
     * @param id
     */
    public void delivery(Long id) {
        //根据id查询订单
        Orders orderDB = orderMapper.getById(id);
        //校验订单是否存在，并且状态为3
        if(orderDB == null || !Orders.CONFIRMED.equals(orderDB.getStatus())){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders order = Orders.builder()
                .id(id)
                .status(Orders.DELIVERY_IN_PROGRESS)
                .estimatedDeliveryTime(LocalDateTime.now()).build();
        orderMapper.update(order);
    }

    /**
     * 完成订单
     * @param id
     */
    public void complete(Long id) {
        //根据订单id查询订单
        Orders orderDB=orderMapper.getById(id);
        //订单是否存在，并且状态为4
        if(orderDB == null || !Orders.DELIVERY_IN_PROGRESS.equals(orderDB.getStatus())){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders order=Orders.builder()
                .id(id)
                .status(Orders.COMPLETED)//订单状态变为完成
                .deliveryTime(LocalDateTime.now()).build();
        orderMapper.update(order);
    }

    /**
     * 用户催单
     * @param id
     */
    public void reminder(Long id) {
        //查询订单是否存在
        Orders order = orderMapper.getById(id);
        if(order== null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //基于websocket实现用户催单
        Map map=new HashMap();
        map.put(OrderWebSocketConstant.KEY_TYPE,OrderWebSocketConstant.VALUE_TYPE_CUSTOMER_REMINDER);//用户催单
        map.put(OrderWebSocketConstant.KEY_ORDER_ID,id);
        map.put(OrderWebSocketConstant.KEY_CONTENT,"订单号："+order.getNumber());//获取到订单号
        webSocketServer.sendToAllClient(JSON.toJSONString(map));


    }






}
